package top.yqingyu.httpserver.controller;

import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.yqingyu.httpserver.annotation.QyController;
import top.yqingyu.httpserver.common.HttpMethod;
import top.yqingyu.httpserver.common.MultipartFile;
import top.yqingyu.httpserver.common.Request;
import top.yqingyu.httpserver.common.Session;


import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;

/**
 * @author YYJ
 * @version 1.0.0
 * @ClassName top.yqingyu.httpserver.controller.UploadDemo
 * @description
 * @createTime 2023年01月07日 03:01:00
 */
@QyController(path = "upload")
public class UploadDemo {
    Logger logger = LoggerFactory.getLogger(UploadDemo.class);

    @QyController(path = "path", method = {HttpMethod.GET})
    public String path(String name) {
        return "  <form action=\"/upload/page\" method=\"post\" enctype=\"application/x-www-form-urlencoded\">\n" +
                " <label>保存路径：</label><input type=\"input\" name=\"path\">\n" +
                "    <input type=\"submit\" value=\"upper1\">\n" +
                "  </form>";
    }

    @QyController(path = "page", method = {HttpMethod.POST})
    public String page(JSONObject jsonObject, Request request) {
        logger.info("path : {}", jsonObject.toJSONString());
        Session session = request.getSession();
        session.set("path", jsonObject.get("path"));
        return "  <form action=\"/upload/upper\" method=\"post\" enctype=\"multipart/form-data\">\n" +
                "    <input type=\"file\" name=\"uploadFile\" value=\"请选择文件\">\n" +
                "    <input type=\"submit\" value=\"upper1\">\n" +
                "  </form>";
    }

    @QyController(path = "upper", method = {HttpMethod.POST})
    public String upper(MultipartFile file, Request request) throws IOException, NoSuchFieldException, IllegalAccessException {
        Session session = request.getSession();
        Object path = session.get("path");
        session.clear();
        logger.info("save File : {}{}", path, file.getFileName());
        file.saveAs(path + file.getFileName());
        logger.info("save File success : {}{}", path, file.getFileName());
        Field field = MultipartFile.class.getDeclaredField("file");
        field.setAccessible(true);
        File file2 = (File) field.get(file);
        if (file2.exists()) {
            file2.delete();
            logger.info("delete org File success : {}", file2.getAbsolutePath());
        }
        return "<h1>保存成功</h1>" +
                "<div><a href='/upload/path'>返回</a><div>";
    }
}
